<?php
namespace app\api\controller;
use think\Db;
use app\api\model\CommonModel;

class Message extends Common {
    public function _initialize()
    {
        // todo...
        parent::_initialize();
    }

    public function __construct() //Db::connect('database_app');
    {
        parent::__construct();
        $this->db_app = Db::connect('database_app');
    }


	/**************************** 好友相关 begin  *********************************/

    /**
     * 根据昵称或手机号搜索用户
     * @return array
     */
    public function searchUser() {
        $keyword = input('keyword');
        $userId= input('userId');
        $rongId= input('rongId');

        if (!$userId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数userId";
            return $this->outData;
        }

        if (!$keyword) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数keyword";
            return $this->outData;
        }

        $where = array();
        $where['Id'] = ['<>',$userId];
        if (isTel($keyword)) {
            // 根据电话号码查询
            $where['Username'] = $keyword;
        } else {
            // 根据昵称查询
            $where['Nickname'] = ['like','%'.$keyword.'%'];
        }


        $userList = array();
        $userList = $this->db_app->table('customer')
                    ->field('Id as userId,nickName,avatar as headPic,rongCustomerId as rongId')
                    ->where($where)
                    ->limit('20')
                    ->select();

        $friendList = array();
        $friendList = $this->db_app->table('msg_friend')
            ->field('target_id as rongId')
            ->where('uid',$rongId)
            ->select();

        $friendArray = array();
        foreach ($friendList as $k => $v) {
            $friendArray[$k] = $v['rongId'];
        }

        foreach ($userList as $k => $v) {
            $tempRongId = $userList[$k]['rongId'];
            $userList[$k]['is_friend'] = in_array($tempRongId,$friendArray);
        }

        $this->outData['code'] = 1;
        $this->outData['message'] = "操作成功";
        $this->outData['data'] = $userList;
        return $this->outData;

    }

    //获取好友列表，搜索好友列表的某个好友
    public function friendList()
    {
        $rongId = input('rongId');
        // 是否有参数传入
        if (input('?param.keyword')) {
            $keyword = input('param.keyword');
        } else {
            $keyword = '';
        }

        $userList = $this->db_app->table('msg_friend')
            ->alias('f')
            ->join('customer c', 'f.target_id = c.rongCustomerId')
            ->field('c.Id as userId,c.TrueName,c.NickName,c.avatar as headPic,f.target_id as rongId')
            ->where('f.uid', $rongId)
            ->where('c.NickName', 'like', $keyword . '%')
            ->select();

        if ($userList) {
            $this->outData['data'] = $userList;
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }

        $this->outData['code'] = 3;
        $this->outData['message'] = "暂无数据";
        return $this->outData;
    }


    /**************************** 群相关 begin  *********************************/

    //查询我拥有的群组
    public function myGroup()
    {
        $rongId = input('rongId');
        //加入的群id
        $joinGroup = $this->db_app->table('msg_group_member')
            ->alias('gm')
            ->join('msg_group g', 'gm.group_id = g.id')
            ->field('g.id,g.name,g.avatar')
            ->where('gm.uid',$rongId)
            ->select();
        if($joinGroup){
            $this->outData['data'] = $joinGroup;
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 3;
            $this->outData['message'] = "暂无数据";
            return $this->outData;
        }
    }

    /**
     * 获取群相关的数据
     * @return array
     */
    public function getGroupRelated()
    {
        $groupId = input('groupId');
        $rongId  = input('rongId');
        if (!$groupId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数groupId";
            return $this->outData;
        }

        if (!$rongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数rongId";
            return $this->outData;
        }


        $data = array('groupName'=>'','groupAvatar'=>'','groupOwerId'=>'','mynameInGroup'=>'','announcement'=>'','groupMemberList'=>array());

        $groupInfo = $this->db_app->table('msg_group')
            ->field('name,avatar,owner_id,announcement')
            ->where('id',$groupId)
            ->find();
        if (!$groupInfo) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "群不存在";
            return $this->outData;
        }
        $data['groupName'] = $groupInfo['name'];
        $data['groupAvatar'] = $groupInfo['avatar'];
        $data['groupOwerId'] = $groupInfo['owner_id'];
        $data['announcement'] = $groupInfo['announcement'];


        $memberInfo = $this->db_app->table('msg_group_member')
            -> alias('gm')
            -> join('customer c','gm.uid = c.rongCustomerId')
            ->field('gm.uid,c.nickName,c.Avatar as headPic,gm.groupnick,c.rongCustomerId as rongId')
            ->where('gm.group_id',$groupId)
            ->order('gm.is_groupmaster desc')
            ->select();

        if($memberInfo){
            $info = array();
            foreach($memberInfo as $k => $v) {
                $info[$k]['nickName'] = $v['nickName'];
                $info[$k]['headPic'] = $v['headPic'];
                $info[$k]['groupnick'] = $v['groupnick'];
                $info[$k]['rongId'] = $v['rongId'];
                if ($v['uid'] == $rongId) {
                    if (!$info[$k]['groupnick']) {
                        $data['mynameInGroup'] = $info[$k]['nickName'];
                    } else {
                        $data['mynameInGroup'] = $info[$k]['groupnick'];
                    }
                }
            }

            $data['groupMemberList'] = $info;
            $this->outData['data'] = $data;
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 3;
            $this->outData['message'] = "暂无数据";
            return $this->outData; 
        }
    }
    //创建群
    public function createGroup()
    {
        $rongId = input('rongId');
        $groupName = input('groupName');
        $rongIdArr = explode('-', $rongId);

        $group = array();
        $group['name'] = $groupName;
        $group['avatar'] = 'http://images2017.cnblogs.com/blog/422101/201711/422101-20171110140445919-283240225.png';
        $group['owner_id'] = $rongIdArr[0];
        $group['create_on'] = date('Y-m-d',time());
        $group['update_on'] = date('Y-m-d',time());
        //新增数据并返回主键值
        $groupId = $this->db_app->table('msg_group')->insert($group,false,true,null);
        if($groupId){
            //将群成员添加到群成员表
            $groupMember = array();
            $res_bool = false;
            foreach($rongIdArr as $v){
                $groupMember[] = array(
                        'group_id' => $groupId,
                        'uid'      => $v,
                        'is_groupmaster' => $res_bool == false ? 1 : 0,
                        'create_on'=> date('Y-m-d',time())
                    );
                $res_bool = ture;
            }
            $result = $this->db_app->table('msg_group_member')->insertAll($groupMember);
            if($groupId && $result){
                $rongIdArr[] = $rongIdArr[0];
                $result_json = $this->rong_cloud->group()->create($rongIdArr,$groupId,$groupName);
                $result_array=json_decode($result_json,true);
                if ($result_array['code']==200) {
                    $this->outData['code'] = 1;
                    $this->outData['message'] = "操作成功";
                    $this->outData['data'] = $groupId;
                    return $this->outData;
                }
            }
        }
        $this->outData['code'] = 2;
        $this->outData['message'] = "操作失败";
        return $this->outData;
    }
    //解散群
    public function dismissGroup()
    {
        $rongId = input('rongId');
        $groupId = input('groupId');
        $groupInfo = $this->db_app->table('msg_group')->where('id',$groupId)->find();

        //判断是否是群主
        if($groupInfo['owner_id'] == $rongId){
            //是群主，解散群
            $result = $this->rong_cloud->group()->dismiss($rongId,$groupId);
            $result_array=json_decode($result,true);
            if ($result_array['code']==200) {
                //融云解散群成功，发送系统消息
                $groupMember = $this->db_app->table('msg_group_member')->field('uid')->where('group_id',$groupId)->select();
                $groupMemberId = array();
                foreach($groupMember as $v){
                    $groupMemberId[] = $v['uid'];
                }
                $content = array();
                $content['content'] = $groupInfo['name'].'已解散';
                $content['extra']   = array("globalId"=>18360174986);
                $content = json_encode($content);
                $result_array = $this->rong_cloud->message()->PublishSystem('1', $groupMemberId, 'RC:TxtMsg',$content, 'thisisapush', '{\"pushData\":\"hello\"}', '0', '0');
                $result_array = json_decode($result_array, true);
                if ($result_array['code']==200) 
                {
                    $this->db_app->table('msg_group')->where('id',$groupId)->delete();
                    $this->db_app->table('msg_group_member')->where('group_id',$groupId)->delete();
                    $this->outData['code'] = 1;
                    $this->outData['message'] = "解散成功";
                    return $this->outData;
                }else {
                    $this->outData['code'] = 2;
                    $this->outData['message'] = "融云解散群成功，但发送系统消息失败";
                    return $this->outData;
                }
            }else{
                $this->outData['code'] = 2;
                $this->outData['message'] = "融云解散群失败";
                return $this->outData;
            }
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "非群主";
            return $this->outData;
        }
    }
    //退出群
    public function quitGroup()
    {
        $userId = input('userId');
        $groupId = input('groupId');
        $rongId = getRongId($userId);
        $result = $this->rong_cloud->group()->quit($rongId,$groupId);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            //融云退出群成功，发送系统消息给群主
            $content = array();
            $content['content'] = getNIckHeadpic($userId)['NickName'].'已退出该群';
            $content['extra']   = array("globalId"=>18360174986);
            $content = json_encode($content);
            $result_array = $this->rong_cloud->message()->PublishSystem('1', $rongId, 'RC:TxtMsg',$content, 'thisisapush', '{\"pushData\":\"hello\"}', '0', '0');
            $result_array = json_decode($result_array, true);
            if ($result_array['code']==200) 
            {
                $this->db_app->table('msg_group_member')->where('group_id',$groupId)->where('uid',$rongId)->delete();
                $this->outData['code'] = 1;
                $this->outData['message'] = "退群成功";
                return $this->outData;
            }else {
                $this->outData['code'] = 2;
                $this->outData['message'] = "融云退群成功，但发送系统消息失败";
                return $this->outData;
            }
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }


    /**
     * 群主删除群成员
     * @author jim
     * @date 2017-11-11
     */
    public function delGroupMember() {
        $groupId = input('groupId');
        $rongId = input('rongId');
        $groupMemberRongId = input('groupMemberRongId');
        $groupMemberRongId = explode('-', $groupMemberRongId);
        $groupInfo = $this->db_app->table('msg_group')->where('id',$groupId)->find();
        if($groupInfo['owner_id'] == $rongId){
            //是群主，融云退出群
            $result_array = $this->rong_cloud->group()->quit($groupMemberRongId, $groupId);
            $result_array = json_decode($result_array, true);
            if($result_array['code']==200){
                //融云移除群成员成功，删除群成员
                $this->db_app->table('msg_group_member')->where('group_id',$groupId)->where('uid','in',$groupMemberRongId)->delete();
                $this->outData['code'] = 1;
                $this->outData['message'] = "操作成功";
                return $this->outData;
            }else{
                $this->outData['code'] = 2;
                $this->outData['message'] = "融云删除群成员失败";
                return $this->outData;   
            }
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "非群主";
            return $this->outData;
        }
    }

    /**
     * 添加群成员
     * @author jim
     * @date 2017-11-11
     */
    public function addGroupMember() {
        $groupId = input('groupId');
        $groupInfo = $this->db_app->table('msg_group')->where('id',$groupId)->find();
        $groupName = $groupInfo['name'];
        $newGroupMemberId = input('memberId');
        $newGroupMemberId = explode('-', $newGroupMemberId);
        $result = $this->rong_cloud->group()->join($newGroupMemberId,$groupId,$groupName);
        $result_array=json_decode($result,true);
        if($result_array['code'] = 200){
            //融云添加群成员成功
            foreach($newGroupMemberId as $v){
                $data[] = array(
                        'group_id' => $groupId,
                        'uid' => $v,
                        'create_on' => date('Y-m-d',time())
                    );
            }
            $res = $this->db_app->table('msg_group_member')->insertAll($data);
            $this->outData['code'] = 1;
            $this->outData['message'] = "添加成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "融云添加群成员失败";
            return $this->outData;
        }
    }


    /**
     * 获取非群成员之外的好友信息
     * @author jim
     * @date 2017-11-11
     */
    public function getFriendNotInGroup() {
        $groupId = input('groupId');
        $userId = input('userId');
        $rongId = getRongId($userId);
        $friendList = $this->db_app->table('msg_friend')->field('target_id')->where('uid',$rongId)->select();
        //构建为一维数组
        foreach($friendList as $v){
            $friendListArr[] = $v['target_id'];
        }
        $memberList = $this->db_app->table('msg_group_member')->field('uid')->where('group_id',$groupId)->select();
        foreach ($memberList as $v) {
            $memberListArr[] = $v['uid'];
        }
        $newArr = array_diff($friendListArr, $memberListArr);
        foreach($newArr as $k => $v){
            $info = getNIckHeadpic(getUserId($v));
            $data[$k]['rongId'] = $v;
            $data[$k]['nickName'] = $info['NickName'];
            $data[$k]['headPic'] = $info['headPic'];
        }
        $this->outData['data'] = $data;
        $this->outData['code'] = 1;
        $this->outData['message'] = "操作成功";
        return $this->outData;
    }



    /***************************************** 同步 **********************************/

    /*
     * 同步群和好友
     * @author jim
     * @date 2017-11-11
     * @return array
     */
    public function  syncAddressBook() {
        $userId = input('userId');
        if (!$userId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数userId";
            return $this->outData;
        }

        $rongId = input('rongId');
        if (!$rongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数rongId";
            return $this->outData;
        }

        $data = array('md5'=>'','list'=>'');
        // 获取群数据
        $groupList = array();
        $groupList = $this->db_app->table('msg_group_member')
            ->alias('gm')
            ->join('msg_group g','gm.group_id = g.id')
            ->where('gm.uid',$rongId)
            ->field('g.name as title,g.id,g.avatar as placeholderImg,g.avatar as img')
            ->select();
        foreach ($groupList as $k => $v) {
            $groupList[$k]['sentTime'] = 0;
            $groupList[$k]['text'] = '';
            $groupList[$k]['t'] = 1;
            $groupList[$k]['messageId'] = 0;
        }

        // 获取好友数据
        $friendList = array();
        $friendList = $this->db_app->table('msg_friend')
            ->alias('f')
            ->join('customer c','f.target_id = c.rongCustomerId')
            ->where('f.uid',$rongId)
            ->field('f.target_id as id,c.NickName as title,c.Username as login_name,c.avatar as img,c.avatar as placeholderImg')
            ->select();


         foreach ($friendList as $k => $v) {
             $friendList[$k]['text'] = '';
             $friendList[$k]['sentTime'] = 0;
             $friendList[$k]['jp'] = 0;
             $friendList[$k]['messageId'] = 0;
         }

         $list = array();
         $list['common'] = $groupList;
         $list['person'] = $friendList;

         $md5 = md5(serialize($list));

         $data['list'] = $list;
         $data['md5']  = $md5;


        $this->outData['code'] = 1;
        $this->outData['message'] = "操作成功";
        $this->outData['data'] = $data;
        return $this->outData;

    }

    /**
     * 同步群成员
     * @author jim
     * @date 2017-11-11
     * @return array
     */
    public function syncGroupMember() {
        $groupId = input('groupId');

        if (!$groupId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数groupId";
            return $this->outData;
        }

        $data = array('md5'=>'','list'=>'');

        $list = array();
        $groupMemberList = $this->db_app->table('msg_group_member')
            ->alias('gm')
            ->join('customer c','c.rongCustomerId = gm.uid')
            ->where('gm.group_id',$groupId)
            ->order('gm.is_groupmaster desc')
            ->field('gm.uid as person_id,c.NickName as person_name,c.Username as login_name,c.avatar as head_img')
            ->select();


        $list = $groupMemberList;
        $md5 = md5(serialize($list));
        $data['list'] = $list;
        $data['md5']  = $md5;


        $this->outData['code'] = 1;
        $this->outData['message'] = "操作成功";
        $this->outData['data'] = $data;
        return $this->outData;
    }

    /**
     * 刷新token
     */
    public function refreshRongToken() {
        $rongId = input('rongId');
        $userId = input('userId');
        if (!$rongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数rongId";
            return $this->outData;
        }

        if (!$userId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数userId";
            return $this->outData;
        }

        // 刷新rongToken，保存token到数据库，返回token值给app
        $commonModel = new CommonModel();
        $userInfo = $commonModel->getUserInfo($rongId);

        $result_array = $this->rong_cloud->user()->getToken($rongId, $userInfo['nickName'], $userInfo['avatar']);
        print_r($result_array);

        $result_array = json_decode($result_array, true);



        if ($result_array['code']==200) {
            // 保存token到数据库
            $this->db_app->table('customer')
                ->where('Id',$userId)
                ->update(['rongToken'=>$result_array['token']]);

            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['token'] = $result_array['token'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }

    }


    /***************************************** 好友申请 **********************************/
    /**
     * 申请好友
     * @author jim
     * @date 2017-11-11
     * @return array
     */
    public function applyFriend() {
        $rongId = input('rongId');
        $targetRongId = input('targetRongId');
        $content    = input('content','申请备注:无');

        if (!$rongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数rongId";
            return $this->outData;
        }

        if (!$targetRongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数targetRongId";
            return $this->outData;
        }

        // 检查他们是否已经是好友
        $friendData = $this->db_app->table('msg_friend')
            ->where('uid',$rongId)
            ->where('target_id',$targetRongId)
            ->find();

        if ($friendData) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "已是好友";
            return $this->outData;
        }

        // 检查正在处理申请记录是否存在
        $applyData = $this->db_app->table('msg_friend_apply')
            ->where('uid',$rongId)
            ->where('target_id',$targetRongId)
            ->where('status',1)
            ->find();

        if ($applyData) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "申请已存在，请耐心等待";
            return $this->outData;
        }

        // 创建申请记录
        $sendApplyId =  $this->db_app->table('msg_friend_apply')->insert([
            'uid' => $rongId,
            'target_id' => $targetRongId,
            'content' => $content,
            'created_on' => date('Y-m-d H:i:s',time()),
            'update_on' => date('Y-m-d H:i:s',time()),
            'status' => 1
        ],false,true);
        
        $commonModel = new CommonModel();
        $rongNickName = $commonModel->getUserInfo($rongId,$commonModel::TYPE_NAME);
        $targetNickName = $commonModel->getUserInfo($targetRongId,$commonModel::TYPE_NAME);


        $content_uid = "申请加".$targetNickName."为好友成功，请等待";
        // 发送系统消息
        $result_uid = $this->sendSysMsg($rongId,$content_uid,"申请好友成功");

        $content_target = $rongNickName."申请加您为好友，请处理";
        $result_target = $this->sendSysMsg($targetRongId,$content_target,"有好友申请，请处理");

        if ($result_uid['code'] == 200 && $result_target['code'] == 200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "申请成功，请耐心等待";
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "申请成功，系统消息有误";
            return $this->outData;
        }
    }

    /**
     * 处理申请,同意或者拒绝好友申请
     * @author jim
     * @date 2017-11-11
     * @return array
     */
    public function dealApply() {
        $applyId = input('applyId');
        if (!$applyId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数applyId";
            return $this->outData;
        }

        $operate = input('operate'); // 1 同意 2 拒绝
        if (!$operate) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数operate";
            return $this->outData;
        }

        // 获取基本信息
        $applyInfo = $this->db_app->table('msg_friend_apply')
                        ->where('id',$applyId)
                        ->where('status',1)
                        ->find();

        if (!$applyInfo) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "申请已处理";
            return $this->outData;
        }


        // 获取申请人和目标人的rongId
        $applyRongId = $applyInfo['uid'];
        $yourRongId = $applyInfo['target_id'];

        $commonModel = new CommonModel();
        $applyNickName = $commonModel->getUserInfo($applyRongId,$commonModel::TYPE_NAME);
        $yourNickName = $commonModel->getUserInfo($yourRongId,$commonModel::TYPE_NAME);

        if ($operate == 1) {
            // 同意成为好友
            $this->db_app->table('msg_friend_apply')
                ->where('id',$applyInfo['id'])
                ->update(['status'=>2,'update_on'=>date('Y-m-d H:i:s',time())]);

            // 判断好友关系是否存在
            $friendInfo = $this->db_app->table('msg_friend')->where('uid',$applyRongId)->where('target_id',$yourRongId)->find();

            if (!$friendInfo) {
                // 建立新的好友数据
                $this->db_app->table('msg_friend')->insert([
                    'uid' => $applyRongId,
                    'target_id' => $yourRongId,
                    'is_star' => '1',
                    'created_on' => date('Y-m-d',time()),
                    'update_on' => date('Y-m-d',time()),
                ]);

                $this->db_app->table('msg_friend')->insert([
                    'uid' => $yourRongId,
                    'target_id' => $applyRongId,
                    'is_star' => '1',
                    'created_on' => date('Y-m-d',time()),
                    'update_on' => date('Y-m-d',time()),
                ]);
                $this->sendSysMsg($yourRongId,"您同意了".$applyNickName."的好友申请","好友申请处理");
                $this->sendSysMsg($applyRongId,$yourNickName."同意了您的好友申请","好友申请处理");
            }

        } else {
            // 拒绝成为好友
            $this->db_app->table('msg_friend_apply')
                ->where('id', $applyInfo['id'])
                ->update(['status' => 3, 'update_on' => date('Y-m-d H:i:s', time())]);


            $this->sendSysMsg($yourRongId, "您拒绝了" . $applyNickName . "的好友申请", "好友申请处理");

            $this->sendSysMsg($applyRongId, $yourNickName . "拒绝了您的好友申请", "好友申请处理");
        }


        $this->outData['code'] = 1;
        $this->outData['message'] = "操作成功";
        return $this->outData;

    }

    /**
     * 获取申请列表接口
     * @author jim
     * @date 2017-11-11
     * @return array
     */
    public function getApplyList() {
        $rongId = input('rongId');

        if (!$rongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数rongId";
            return $this->outData;
        }

        $applyList = $this->db_app->table('msg_friend_apply fa')
            ->where('fa.uid',$rongId)
            ->whereOr('fa.target_id',$rongId)
            ->join('customer c','uid = c.rongCustomerId')
            ->join('customer tc','target_id = tc.rongCustomerId')
            ->order('fa.id desc')
            ->field('fa.id as applyId,fa.uid as rongId,fa.content,fa.target_id as targetId,fa.status,fa.from_del,fa.to_del,c.NickName as uNickName,c.avatar as uAvatar,tc.NickName as tNickName,tc.avatar as tAvatar')
            ->select();


        $applyListOut = array();
        $tmp_key = 0;
        foreach ($applyList as $k=>$v) {

            if ($v['rongId'] == $rongId) {
                if ($v['from_del'] == 0) {
                    $applyListOut[$tmp_key]['applyId']    = $v['applyId'];
                    $applyListOut[$tmp_key]['content']    = $v['content'];
                    $applyListOut[$tmp_key]['status']    = $v['status'];

                    $applyListOut[$tmp_key]['rongId']     = $v['rongId'];
                    $applyListOut[$tmp_key]['targetId']   = $v['targetId'];
                    // 你发送的
                    $applyListOut[$tmp_key]['targetNickname'] = $v['tNickName'];
                    $applyListOut[$tmp_key]['targetAvatar'] = $v['tAvatar'];

                    $applyListOut[$tmp_key]['direction'] = 2; // 发送的

                    $tmp_key++;
                }

            } else {
                if ($v['to_del'] == 0) {
                    $applyListOut[$tmp_key]['applyId']    = $v['applyId'];
                    $applyListOut[$tmp_key]['content']    = $v['content'];
                    $applyListOut[$tmp_key]['status']    = $v['status'];

                    $applyListOut[$tmp_key]['rongId']     = $v['targetId'];
                    $applyListOut[$tmp_key]['targetId']   = $v['rongId'];
                    // 发给你的
                    $applyListOut[$tmp_key]['targetNickname'] = $v['uNickName'];
                    $applyListOut[$tmp_key]['targetAvatar'] = $v['uAvatar'];

                    $applyListOut[$tmp_key]['direction'] = 1; // 接收的
                    $tmp_key++;
                }
            }


        }

        $this->outData['code'] = 1;
        $this->outData['message'] = "获取成功";
        $this->outData['data'] = $applyListOut;
        return $this->outData;


    }

    /**
     * 获取未处理的申请数量
     * @author jim
     * @date 2017-11-11
     * @return array
     */
    public function getUndealApplyCount() {
        $rongId = input('rongId');

        if (!$rongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数rongId";
            return $this->outData;
        }

        $count = $this->db_app->table('msg_friend_apply')
            ->where('target_id',$rongId)
            ->where('status',1)
            ->count();

        $this->outData['code'] = 1;
        $this->outData['message'] = "操作成功";
        $this->outData['data'] = $count;
        return $this->outData;
    }


    /**
     * 删除申请数据
     * @author jim
     * @date 2017-11-11
     * @return array
     */
    public function delApply() {
        $applyId = input('applyId');

        $rongId = input('rongId');

        // 判断是否已经处理过
        $applyInfo = $this->db_app->table('msg_friend_apply')
            ->where('id',$applyId)
            ->find();

        if ($applyInfo['status'] == '1') {
            $this->outData['code'] = 2;
            $this->outData['message'] = "未被处理的消息";
            return $this->outData;
        }

        if ($applyInfo['uid'] == $rongId) {
            $res =  $this->db_app->table('msg_friend_apply')
                ->where('id',$applyId)
                ->update(['from_del'=>1,'update_on'=>date('Y-m-d H:i:s',time())]);
        } else {
            $res =  $this->db_app->table('msg_friend_apply')
                ->where('id',$applyId)
                ->update(['to_del'=>1,'update_on'=>date('Y-m-d H:i:s',time())]);
        }


        if ($res) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "删除成功";
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "删除失败";
            return $this->outData;
        }
    }



    //加好友
    public function addFriend()
    {
        $rongId = input('rongId');
        $targetRongId = input('targetRongId');
        $this->db_app->table('msg_friend')->insert([
            'uid' => $rongId,
            'target_id' => $targetRongId,
            'is_star' => '1',
            'created_on' => date('Y-m-d',time()),
            'update_on' => date('Y-m-d',time()),
        ]);

        $this->db_app->table('msg_friend')->insert([
            'uid' => $targetRongId,
            'target_id' => $rongId,
            'is_star' => '1',
            'created_on' => date('Y-m-d',time()),
            'update_on' => date('Y-m-d',time()),
        ]);

        $this->outData['code'] = 1;
        $this->outData['message'] = "添加好友成功";
        return $this->outData;
    }
    //删除好友
    public function delFriend()
    {
        $rongId = input('rongId');
        $targetRongId = input('targetRongId');

        $this->db_app->table('msg_friend')->where('uid',$rongId)->where('target_id',$targetRongId)->delete();
        $this->db_app->table('msg_friend')->where('uid',$targetRongId)->where('target_id',$rongId)->delete();
        $this->outData['code'] = 1;
        $this->outData['message'] = "删除好友成功";
        return $this->outData;
    }

    //好友备注
    public function noteFriend()
    {
        $note = input('note');
        $rongId = input('rongId');
        $targetRongId = input('targetRongId');
        $this->db_app->table('msg_friend')->where('uid',$rongId)->where('target_id',$targetRongId)->update(['note'=>$note]);
        $this->outData['code'] = 1;
        $this->outData['message'] = "备注成功";
        return $this->outData;
    }

    //查看通讯录好友
    public function addressListFriend()
    {
        $userId = input('userId');
        $rongId = getRongId($userId);
        $tel = input('tel');
        $tel = explode('-', $tel);
        foreach($tel as $v){
            $newTel[] = substr($v,-11);//如果号码不足11位，返回false
        }
        $addressList = $this->db_app->table('customer')->field('Id,TrueName,NickName')->where('Username','in',$newTel)->select();
        //查询好友列表
        $friendList = $this->db_app->table('msg_friend')->field('target_id')->where('uid',$rongId)->select();
        foreach($friendList as $v){
            $friendListArr[] = $v;
        }
        $data = array();
        foreach($addressList as $k => $v){
            $data[$k]['userId'] = $v['Id'];
            $data[$k]['nickName'] = $v['NickName'];
            $data[$k]['trueName'] = $v['TrueName'];
            $rongId = $data[$k]['rongId'] = getRongId($v['Id']);
            $info = $this->db_app->table('genericattribute')->field('Value')->where('EntityId',$v['Id'])->where('Key','Avatar')->find();
            $data[$k]['headPic'] = $info['Value'];
            if(in_array($rongId, $friendListArr)){
                $data[$k]['inMyFriend'] = true;
            }else{
                $data[$k]['inMyFriend'] = false;
            }
        }
        $this->outData['data'] = $data;   
        $this->outData['code'] = 1;
        $this->outData['message'] = "操作成功";
        return $this->outData;
    }



    //群名称修改
    public function updateGroupName()
    {
        $userId = input('userId');
        $rongId = getRongId($userId);
        $groupId = input('groupId');
        $groupName = input('groupName');
        $groupInfo = $this->db_app->table('msg_group')->where('id',$groupId)->find();
        //判断是否是群主
        if($groupInfo['owner_id'] == $rongId){
            //是群主，修改群名称
            $result = $this->rong_cloud->group()->refresh($groupId,$groupName);
            $result_array=json_decode($result,true);
            if ($result_array['code']==200) {
                //融云刷新群组信息成功
                $this->db_app->table('msg_group')->where('id',$groupId)->update(['name'=>$groupName]);
                $this->outData['code'] =1;
                $this->outData['message'] = "操作成功";
                return $this->outData;
            }else{
                $this->outData['code'] = 2;
                $this->outData['message'] = "融云刷新群组信息失败";
                return $this->outData;
            }
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "非群主";
            return $this->outData;
        }
    }
    //群头像修改
    public function updateGroupAvatar()
    {
        $userId = input('userId');
        $rongId = getRongId($userId);
        $groupId = input('groupId');
        $groupAvatar = input('groupAvatar');
        $groupInfo = $this->db_app->table('msg_group')->where('id',$groupId)->find();
        //判断是否是群主
        if($groupInfo['owner_id'] == $rongId){

            //是群主，修改群头像
            $res = $this->db_app->table('msg_group')->where('id',$groupId)->update(['avatar'=>$groupAvatar]);
            if ($res) {
                $this->outData['code'] = 1;
                $this->outData['message'] = "修改群头像成功";
                return $this->outData;
            } else {
                $this->outData['code'] = 2;
                $this->outData['message'] = "修改群头像失败";
                return $this->outData;
            }

        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "非群主";
            return $this->outData;
        }
    }
    //我在本群中的昵称设置
    public function myNameInGroup()
    {
        $userId = input('userId');
        $rongId = getRongId($userId);
        $groupId = input('groupId');
        $groupnick = input('groupnick');
        $res = $this->db_app->table('msg_group_member')->where('group_id',$groupId)->where('uid',$rongId)->update(['groupnick'=>$groupnick]);
        if($res){
            $this->outData['code'] = 1;
            $this->outData['message'] = "设置成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "设置失败";
            return $this->outData;
        }
    }
    //群公告设置
    public function groupAnnouncement()
    {
        $userId = input('userId');
        $rongId = getRongId($userId);
        $groupId = input('groupId');
        $groupAnnouncement = input('groupAnnouncement');
        $groupInfo = $this->db_app->table('msg_group')->where('id',$groupId)->find();
        //判断是否是群主
        if($groupInfo['owner_id'] == $rongId){
            //是群主，修改群公告
            $this->db_app->table('msg_group')->where('id',$groupId)->update(['announcement'=>$groupAnnouncement]);
            $this->outData['code'] = 1;
            $this->outData['message'] = "修改群公告成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "非群主";
            return $this->outData;
        }
    }

    //设置消息免打扰
    public function setNotification()
    {
        $conversationType = input('conversationType');
        $requestId = input('requestId');
        $targetId = input('targetId');
        $isMuted = input('isMuted');
        $result = $this->rong_cloud->message()->setNotification($conversationType,$requestId,$targetId,$isMuted);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            //融云设置消息免打扰成功
            if($conversationType == '1'){//二人会话
                $this->db_app->table('msg_friend')->where('uid',$requestId)->where('target_id',$targetId)->update(['ismuted' => $isMuted]);
            } else if($conversationType == '3') {//群组会话
                $this->db_app->table('msg_group_member')->where('uid',$requestId)->where('group_id',$targetId)->update(['ismuted' => $isMuted]);
            }
            $this->outData['code'] = 1;
            $this->outData['message'] = "设置成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "融云设置失败";
            return $this->outData; 
        }
    }
    //查询消息免打扰状态
    public function getNotification()
    {
        $conversationType = input('conversationType');
        $requestId = input('requestId');
        $targetId = input('targetId');
        $result = $this->rong_cloud->message()->getNotification($conversationType,$requestId,$targetId);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['data'] = $result_array['isMuted'];
            $this->outData['code'] = 1;
            $this->outData['message'] = "查询成功";
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "融云查询失败";
            return $this->outData;
        }
    }



    /**
     * 获取用户信息
     */
    public function getUserInfo() {
        $rongId = input('rongId');
        if (!$rongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数rongId";
            return $this->outData;
        }

        $commonModel = new CommonModel();
        $userInfo = $commonModel->getUserInfo($rongId);

        if ($userInfo) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            $this->outData['data'] = $userInfo;
            return $this->outData;
        } else {
            $this->outData['code'] = 3;
            $this->outData['message'] = "暂无数据";
            return $this->outData;
        }

    }



    /**
     * 获取用户详情
     * @author jim
     * @date 2017-11-15
     */
    public function getUserDetail() {
        $targetRongId = input('targetRongId');
        $rongId = input('rongId');
        if (!$rongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数rongId";
            return $this->outData;
        }

        if (!$targetRongId) {
            $this->outData['code'] = 2;
            $this->outData['message'] = "缺少参数targetRongId";
            return $this->outData;
        }

        $commonModel = new CommonModel();
        $userInfo = $commonModel->getUserInfo($targetRongId);

        if ($userInfo) {
            $friend = $this->db_app->table('msg_friend')
                ->where('uid',$rongId)
                ->where('target_id',$targetRongId)
                ->find();

            if ($friend) {
                $userInfo['isFriend'] = 1;
            } else {
                $userInfo['isFriend'] = 0;
            }

            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            $this->outData['data'] = $userInfo;
            return $this->outData;
        } else {
            $this->outData['code'] = 3;
            $this->outData['message'] = "暂无数据";
            return $this->outData;
        }
    }

    
}